/*********************************************************************************
 *      Copyright:  (C) 2022 YanlinZhou<1222>
 *                  All rights reserved.
 *
 *       Filename:  get_temperature_ds18b20.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/10/2022)
 *         Author:  YanlinZhou <1222>
 *      ChangeLog:  1, Release initial version on "04/10/2022 08:45:50 PM"
 *                 
 ********************************************************************************/

#include "ds18b20.h"

float get_temperature(float *temp)
{
	char			DR[128] = "/sys/bus/w1/devices/";
	DIR * 			dirp = NULL;
	int				rv = -1;
	struct 			dirent *rdir = NULL;
	char *			dir28 = NULL;
	char *			DR1 = NULL;
	char *			DR2 = NULL;
	char *			name = NULL;
	int				fd = 0;
	char  			*buf = NULL;
	char *			tdir = NULL;

	dirp = opendir(DR);
	if(dirp == NULL )
	{
		printf("Opendir failure:%s\n", strerror(errno));
		rv = -1;
		return -1;
	}

	while( (rdir = readdir(dirp)) != NULL )
	{
		if( (dir28 = (strstr( rdir->d_name, "28-" ))) != NULL )
		{
//			printf("Find 28-: %s \n", dir28);
			DR1 = strcat( DR , dir28);
			DR2 = strcat(DR1, "/w1_slave");
//			printf("The last directory is : %s \n", DR2);
		}

//		printf("Readir : %s \n", rdir->d_name);
	}

	fd = open(DR2, O_RDONLY);
	if(fd < 0 )
	{
		printf("Open file failure:%s\n", strerror(errno));
		return -2;
	}

	buf = malloc(128);
	rv = read(fd, buf, 128);
	close(fd);
//	printf(" rv = %d\n",rv);
	if(rv < 0)
	{
		printf("Read from file w1_salve failure:%s\n", strerror(errno));
		return -3;
	}
//	printf("Read: %s \n from file w1_slave!\n", buf);

	tdir = strstr(buf, "t=");
	if( tdir == NULL)
	{
		printf("Str t= : failure:%s\n",strerror(errno));
		return -4;
	}
	tdir = tdir+2;
	*temp = atof(tdir)/1000;

	return 1;
}

